/*
 * 广州丰石科技有限公司拥有本软件版权2020并保留所有权利。
 * Copyright 2020, Guangzhou Rich Stone Data Technologies Company Limited,
 * All rights reserved.
 */
package demo.idempotent.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.richstonedt.rziomp.common.enums.ExceptionEnum;
import com.richstonedt.rziomp.common.utils.ServletUtils;
import demo.idempotent.annotation.RepeatSubmit;
import demo.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * <b><code>RepeatSubmitInterceptor</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 2020/12/28 6:00 下午.
 *
 * @author wyfd
 * @since rziomp-be 1.0.0
 */
@Slf4j
@Component
public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //RepeatSubmit校验
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null) {
                if (isRepeatSubmit(request)) {
                    R r = new R(ExceptionEnum.TIP_REPEAT_SUBMIT);
                    ServletUtils.renderString(response, JSONObject.toJSONString(r));
                    log.warn("{},{}", ExceptionEnum.TIP_REPEAT_SUBMIT.getMessage(), request.getRequestURI());
                    return false;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    /**
     * @param request
     * @return
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request);
}
